package com.collegeproject.weatherapp.library;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

public class HTTPfunctions extends AsyncTask<String, Void, String> {
	ProgressDialog asycdialog;
	public AsyncResponse listener = null;
	Context _context;
	String _method;
	HttpEntity _postEntity; // for POST
	String _authHeader;

	private static final String POST = "POST";
	private static final String POSTAUTH = "POSTAUTH";
	// private static final String GET = "GET";
	private static final String GETAUTH = "GETAUTH";
	private static final String DELETE = "DELETE";

	public HTTPfunctions() {
	}

	// GET
	public HTTPfunctions(Context context) {
		_context = context;
		_method = "";
	}

	// GET / DELETE AUTH
	public HTTPfunctions(Context context, String method, String authHeader) {
		_context = context;
		_method = method;
		_authHeader = authHeader;
	}

	// POST
	public HTTPfunctions(Context context, String method, HttpEntity postEntity) {
		_context = context;
		_postEntity = postEntity;
		_method = method;
	}

	// POST AUTH
	public HTTPfunctions(Context context, String method, HttpEntity postEntity,
			String authHeader) {
		_context = context;
		_postEntity = postEntity;
		_method = method;
		_authHeader = authHeader;
	}

	@Override
	protected void onPreExecute() {
		// dialog while Async task works
		asycdialog = new ProgressDialog(_context);
		// asycdialog.setTitle("Please Wait");
		asycdialog.setMessage("Loading...");
		asycdialog.show();
		super.onPreExecute();
	}

	@Override
	protected String doInBackground(String... urls) {
		String output = null;

		// deciding whether GET or POST
		if (_method == POSTAUTH) {
			for (String url : urls) {
				output = postHTTPfromURL(url, _postEntity, _authHeader);
			}
		} else if (_method == GETAUTH) {
			for (String url : urls) {
				output = getHTTPfromURL(url, _authHeader);
			}
		} else if (_method == POST) {
			for (String url : urls) {
				output = postHTTPfromURL(url, _postEntity);
			}
		} else if (_method == DELETE) {
			for (String url : urls) {
				output = deleteHTTPfromURL(url, _authHeader);
			}
		} else { // GET
			for (String url : urls) {
				output = getHTTPfromURL(url);
			}
		}
		return output;
	}

	@Override
	protected void onPostExecute(String result) {
		// passing the return string to the class that called it
		listener.processFinish(result);
		asycdialog.dismiss();
	}

	// POST AUTH Method
	private static String postHTTPfromURL(String url, HttpEntity _postBody,
			String _authString) {
		InputStream is = null;
		String result = "";
		try {
			DefaultHttpClient httpclient = new DefaultHttpClient();
			HttpPost httpost = new HttpPost(url);
			httpost.setEntity(_postBody);
			httpost.setHeader("Accept", "application/raw");
			httpost.setHeader("Content-type", "application/raw");
			httpost.setHeader("Authorization", "Basic " + _authString);

			HttpResponse response = httpclient.execute(httpost);
			HttpEntity entity = response.getEntity();
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode == 200) {
				is = entity.getContent();
				result = entityToString(is);
			}
		} catch (UnsupportedEncodingException e) {
			Log.e("POST AUTH HTTP", "Error in http connection " + e.toString());
		} catch (ClientProtocolException e) {
			Log.e("POST AUTH HTTP", "Error in http connection " + e.toString());
		} catch (IOException e) {
			Log.e("POST AUTH HTTP", "Error in http connection " + e.toString());
		}
		return result;
	}

	// POST Method
	private static String postHTTPfromURL(String url, HttpEntity _postBody) {
		InputStream is = null;
		String result = "";
		try {
			DefaultHttpClient httpclient = new DefaultHttpClient();
			HttpPost httpost = new HttpPost(url);
			httpost.setEntity(_postBody);
			httpost.setHeader("Accept", "application/raw");
			httpost.setHeader("Content-type", "application/raw");

			HttpResponse response = httpclient.execute(httpost);
			HttpEntity entity = response.getEntity();
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode == 200) {
				is = entity.getContent();
				result = entityToString(is);
			}
		} catch (UnsupportedEncodingException e) {
			Log.e("POST HTTP", "Error in http connection " + e.toString());
		} catch (ClientProtocolException e) {
			Log.e("POST HTTP", "Error in http connection " + e.toString());
		} catch (IOException e) {
			Log.e("POST HTTP", "Error in http connection " + e.toString());
		}
		return result;
	}

	// HTTP GET with AUTH header
	private static String getHTTPfromURL(String url, String authString) {
		InputStream is = null;
		String result = "";
		try {
			HttpClient httpclient = new DefaultHttpClient();
			HttpGet httpget = new HttpGet(url);
			httpget.setHeader("Authorization", "Basic " + authString);
			HttpResponse response = httpclient.execute(httpget);
			HttpEntity entity = response.getEntity();
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode == 200) {
				is = entity.getContent();
				result = entityToString(is);
			}
		} catch (UnsupportedEncodingException e) {
			Log.e("GET AUTH", "Error in http connection " + e.toString());
		} catch (ClientProtocolException e) {
			Log.e("GET AUTH", "Error in http connection " + e.toString());
		} catch (IOException e) {
			Log.e("GET AUTH", "Error in http connection " + e.toString());
		}
		return result;
	}

	// HTTP DELETE AUTH header
	private static String deleteHTTPfromURL(String url, String authString) {
		InputStream is = null;
		String result = "";
		try {
			HttpClient httpclient = new DefaultHttpClient();
			HttpDelete httpDelete = new HttpDelete(url);
			httpDelete.setHeader("Authorization", "Basic " + authString);

			// Log.i("HTTP DELETE", httpDelete.toString());

			HttpResponse response = httpclient.execute(httpDelete);
			HttpEntity entity = response.getEntity();
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode == 200) {
				is = entity.getContent();
				result = entityToString(is);
			} else {
				Log.i("HTTP DELETE", "return code: " + statusCode);
			}
		} catch (UnsupportedEncodingException e) {
			Log.e("DELETE AUTH", "Error in http connection " + e.toString());
		} catch (ClientProtocolException e) {
			Log.e("DELETE AUTH", "Error in http connection " + e.toString());
		} catch (IOException e) {
			Log.e("DELETE AUTH", "Error in http connection " + e.toString());
		}
		return result;
	}

	// HTTP GET
	private static String getHTTPfromURL(String url) {
		InputStream is = null;
		String result = "";
		try {
			HttpClient httpclient = new DefaultHttpClient();
			HttpGet httpget = new HttpGet(url);
			HttpResponse response = httpclient.execute(httpget);
			HttpEntity entity = response.getEntity();
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode == 200) {
				is = entity.getContent();
				result = entityToString(is);
			}
		} catch (UnsupportedEncodingException e) {
			Log.e("POST GET", "Error in http connection " + e.toString());
		} catch (ClientProtocolException e) {
			Log.e("POST GET", "Error in http connection " + e.toString());
		} catch (IOException e) {
			Log.e("POST GET", "Error in http connection " + e.toString());
		}
		return result;
	}

	private static String entityToString(InputStream is) {
		// convert response to string
		String result = "";
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					is, "iso-8859-1"), 8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			is.close();
			result = sb.toString();
		} catch (Exception e) {
			Log.e("Entity to String ",
					"Error converting result " + e.toString());
		}
		return result;
	}

}